import pymysql
import hashlib


class Dict:
    @staticmethod
    def change_password(password):
        hash = hashlib.sha256()
        hash.update(password.encode())
        return hash.hexdigest()

    def __init__(self):
        self.db = pymysql.connect(user="devil", password="123456", database="dict", charset="utf8")
        self.cur = self.db.cursor()

    def close(self):
        self.db.close()
        self.cur.close()

    def register(self, user, password):
        password = self.change_password(password)
        sql = "insert into user (user, password) values (%s, %s);"
        try:
            self.cur.execute(sql, [user, password])
            self.db.commit()
            return True
        except:
            self.db.rollback()

    def login(self, user, password):
        password = self.change_password(password)
        sql = "select id from user where user=%s and password=%s;"
        self.cur.execute(sql, [user, password])
        return self.cur.fetchone()

    def search(self, word):
        sql = "select exp from mydict where word=%s"
        self.cur.execute(sql, [word])
        return self.cur.fetchone()


if __name__ == '__main__':
    db = Dict()
